package com.ming.yourdiary.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class BaseDialog extends Dialog {
  private static final String TAG = "BaseDialog";
  private boolean dismissHasCalled = false;

  public BaseDialog(@NonNull Context context) {
    super(context);
  }

  public BaseDialog(@NonNull Context context, int themeResId) {
    super(context, themeResId);
  }

  protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
    super(context, cancelable, cancelListener);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate = " + this);
  }

  @Override
  public void onAttachedToWindow() {
    super.onAttachedToWindow();
    Log.d(TAG, "onAttachedToWindow = " + this);
  }

  @Override
  protected void onStart() {
    super.onStart();
    Log.d(TAG, "onStart = " + this);
  }

  @Override
  public void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    if (!this.dismissHasCalled) {
      this.safeDismiss();
    }
  }

  @Override
  protected void onStop() {
    super.onStop();
    Log.d(TAG, "onStop = " + this);
  }

  @Deprecated
  public void show() {
    this.dismissHasCalled = false;
    try {
      super.show();
    } catch (Exception e) {
      Log.d(TAG, "super.show() error" + e);
      e.printStackTrace();
    }
    Log.d(TAG, "show" + this);
  }

  public void safeShow() {
    Log.d(TAG, "safeShow" + this);
    try {
      this.show();
    } catch (Exception e) {
      Log.d(TAG, "super.show() error" + e);
      e.printStackTrace();
    }
  }

  @Deprecated
  public void dismiss() {
    this.dismissHasCalled = true;
    try {
      super.dismiss();
    } catch (Exception e) {
      Log.d(TAG, "super.dismiss() error" + e);
      e.printStackTrace();
    }
    Log.d(TAG, "dismiss" + this);
  }

  public void safeDismiss() {
    Log.d(TAG, "safeDismiss" + this);
    try {
      this.dismiss();
    } catch (Exception e) {
      Log.d(TAG, "super.safeDismiss() error" + e);
      e.printStackTrace();
    }
  }
}
